import { isFunction } from 'lodash'
import Vue from 'vue'

export function usePaging(options) {
  const {
    page = 1,
    size = 15,
    fetchFun,
    params = {},
    firstLoading = false,
    beforeRequest,
    afterRequest
  } = options

  // 记录初始参数
  const paramsInit = Object.assign({}, params)

  // 分页数据
  const pager = Vue.observable({
    page,
    size,
    loading: firstLoading,
    count: 0,
    lists: [],
    extend: {}
  })

  // 请求数据
  function getLists() {
    pager.loading = true
    let requestParams = isFunction(beforeRequest) ? beforeRequest({ ...params }) : params

    return fetchFun({
      pageNo: pager.page,
      pageSize: pager.size,
      ...requestParams
    })
      .then((res) => {
        pager.count = res?.count || res?.total || 0
        pager.lists = res?.lists || res?.list || []
        pager.extend = res?.extend || {}
        if (isFunction(afterRequest)) {
          afterRequest(res)
        }
        return res
      })
      .catch((err) => Promise.reject(err))
      .finally(() => {
        pager.loading = false
      })
  }

  // 重置到第一页
  function resetPage() {
    pager.page = 1
    getLists()
  }

  // 重置参数
  function resetParams() {
    Object.assign(params, { ...paramsInit })
    getLists()
  }

  return {
    pager,
    getLists,
    resetParams,
    resetPage
  }
}
